package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author vvv
 * @date 2023-10-31 09 51
 * discription
 */
@Component
public class RedisIdWorker {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public static final long BEGIN_TIMESTAMP = 1698710400L;

    public static final int COUNT_BITS = 32;

    /**
     *  key是业务名称
     * @param key
     * @return
     */
    public long nextId(String key) {
            // 1. 获取时间搓
            LocalDateTime now = LocalDateTime.now();
            long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
            long timestamp = nowSecond - BEGIN_TIMESTAMP;
            String format = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
            // 2. 获取redis自增
            long increment = stringRedisTemplate.opsForValue().increment("icr:" + key + ":" + format);
            // 3. 拼接放回
            return timestamp << COUNT_BITS | increment;
    }
}
